/**
 * 自定义错误类型定义
 * EndoSight-UC 医疗AI系统
 *
 * 提供统一的错误分类和处理机制
 */

// 基础应用错误类
class AppError extends Error {
  constructor(message, statusCode = 500, code = 'INTERNAL_ERROR', details = null) {
    super(message);
    this.name = this.constructor.name;
    this.statusCode = statusCode;
    this.code = code;
    this.details = details;
    this.timestamp = new Date().toISOString();
    this.isOperational = true;

    // 保持堆栈跟踪
    Error.captureStackTrace(this, this.constructor);
  }

  toJSON() {
    return {
      name: this.name,
      message: this.message,
      code: this.code,
      statusCode: this.statusCode,
      details: this.details,
      timestamp: this.timestamp,
      isOperational: this.isOperational
    };
  }
}

// 数据库相关错误
class DatabaseError extends AppError {
  constructor(message, details = null) {
    super(message, 500, 'DATABASE_ERROR', details);
    this.category = 'database';
  }
}

class DatabaseConnectionError extends DatabaseError {
  constructor(message = '数据库连接失败', details = null) {
    super(message, details);
    this.code = 'DATABASE_CONNECTION_ERROR';
    this.statusCode = 503;
  }
}

class DatabaseQueryError extends DatabaseError {
  constructor(message = '数据库查询失败', details = null) {
    super(message, details);
    this.code = 'DATABASE_QUERY_ERROR';
  }
}

// 医疗AI推理相关错误
class MedicalAIError extends AppError {
  constructor(message, details = null) {
    super(message, 500, 'MEDICAL_AI_ERROR', details);
    this.category = 'medical-ai';
  }
}

class AIInferenceError extends MedicalAIError {
  constructor(message = 'AI推理服务不可用', details = null) {
    super(message, details);
    this.code = 'AI_INFERENCE_ERROR';
    this.statusCode = 503;
  }
}

class AIModelTimeoutError extends MedicalAIError {
  constructor(message = 'AI模型推理超时', details = null) {
    super(message, details);
    this.code = 'AI_MODEL_TIMEOUT';
    this.statusCode = 504;
  }
}

class AIModelOverloadError extends MedicalAIError {
  constructor(message = 'AI模型服务过载', details = null) {
    super(message, details);
    this.code = 'AI_MODEL_OVERLOAD';
    this.statusCode = 503;
  }
}

// 认证和授权相关错误
class AuthenticationError extends AppError {
  constructor(message = '认证失败', details = null) {
    super(message, 401, 'AUTHENTICATION_ERROR', details);
    this.category = 'authentication';
  }
}

class AuthorizationError extends AppError {
  constructor(message = '权限不足', details = null) {
    super(message, 403, 'AUTHORIZATION_ERROR', details);
    this.category = 'authorization';
  }
}

class TokenExpiredError extends AuthenticationError {
  constructor(message = '访问令牌已过期', details = null) {
    super(message, details);
    this.code = 'TOKEN_EXPIRED';
  }
}

class InvalidTokenError extends AuthenticationError {
  constructor(message = '无效的访问令牌', details = null) {
    super(message, details);
    this.code = 'INVALID_TOKEN';
  }
}

// 验证相关错误
class ValidationError extends AppError {
  constructor(message = '数据验证失败', details = null) {
    super(message, 400, 'VALIDATION_ERROR', details);
    this.category = 'validation';
  }
}

class FileValidationError extends ValidationError {
  constructor(message = '文件验证失败', details = null) {
    super(message, details);
    this.code = 'FILE_VALIDATION_ERROR';
  }
}

class MedicalImageValidationError extends FileValidationError {
  constructor(message = '医疗图像验证失败', details = null) {
    super(message, details);
    this.code = 'MEDICAL_IMAGE_VALIDATION_ERROR';
  }
}

// 业务逻辑相关错误
class BusinessError extends AppError {
  constructor(message = '业务逻辑错误', details = null) {
    super(message, 422, 'BUSINESS_ERROR', details);
    this.category = 'business';
  }
}

class PatientNotFoundError extends BusinessError {
  constructor(message = '患者信息不存在', details = null) {
    super(message, details);
    this.code = 'PATIENT_NOT_FOUND';
    this.statusCode = 404;
  }
}

class TaskNotFoundError extends BusinessError {
  constructor(message = '评分任务不存在', details = null) {
    super(message, details);
    this.code = 'TASK_NOT_FOUND';
    this.statusCode = 404;
  }
}

class TaskStatusError extends BusinessError {
  constructor(message = '任务状态不正确', details = null) {
    super(message, details);
    this.code = 'TASK_STATUS_ERROR';
  }
}

class DuplicateResourceError extends BusinessError {
  constructor(message = '资源已存在', details = null) {
    super(message, details);
    this.code = 'DUPLICATE_RESOURCE';
    this.statusCode = 409;
  }
}

// 外部服务相关错误
class ExternalServiceError extends AppError {
  constructor(message = '外部服务错误', details = null) {
    super(message, 502, 'EXTERNAL_SERVICE_ERROR', details);
    this.category = 'external-service';
  }
}

class CircuitBreakerOpenError extends ExternalServiceError {
  constructor(message = '服务熔断器已开启', details = null) {
    super(message, details);
    this.code = 'CIRCUIT_BREAKER_OPEN';
    this.statusCode = 503;
  }
}

// 系统相关错误
class SystemError extends AppError {
  constructor(message = '系统错误', details = null) {
    super(message, 500, 'SYSTEM_ERROR', details);
    this.category = 'system';
  }
}

class ConfigurationError extends SystemError {
  constructor(message = '配置错误', details = null) {
    super(message, details);
    this.code = 'CONFIGURATION_ERROR';
  }
}

class ResourceExhaustionError extends SystemError {
  constructor(message = '系统资源耗尽', details = null) {
    super(message, details);
    this.code = 'RESOURCE_EXHAUSTION';
    this.statusCode = 503;
  }
}

// 安全相关错误
class SecurityError extends AppError {
  constructor(message = '安全错误', details = null) {
    super(message, 403, 'SECURITY_ERROR', details);
    this.category = 'security';
  }
}

class SuspiciousActivityError extends SecurityError {
  constructor(message = '检测到可疑活动', details = null) {
    super(message, details);
    this.code = 'SUSPICIOUS_ACTIVITY';
    this.statusCode = 429;
  }
}

class MaliciousFileError extends SecurityError {
  constructor(message = '检测到恶意文件', details = null) {
    super(message, details);
    this.code = 'MALICIOUS_FILE';
    this.statusCode = 451;
  }
}

// 错误严重程度枚举
export const ErrorSeverity = {
  LOW: 'low',
  MEDIUM: 'medium',
  HIGH: 'high',
  CRITICAL: 'critical'
};

// 错误分类工具
export const classifyError = (error) => {
  if (error instanceof AppError) {
    return {
      type: error.constructor.name,
      category: error.category,
      severity: getErrorSeverity(error),
      isOperational: error.isOperational
    };
  }

  // 处理原生错误类型
  if (error.name === 'ValidationError') {
    return {
      type: 'ValidationError',
      category: 'validation',
      severity: ErrorSeverity.LOW,
      isOperational: true
    };
  }

  if (error.name === 'TypeError' || error.name === 'ReferenceError') {
    return {
      type: error.name,
      category: 'programming',
      severity: ErrorSeverity.HIGH,
      isOperational: false
    };
  }

  // 默认分类
  return {
    type: error.name || 'UnknownError',
    category: 'unknown',
    severity: ErrorSeverity.MEDIUM,
    isOperational: false
  };
};

// 根据错误类型确定严重程度
const getErrorSeverity = (error) => {
  if (error instanceof SecurityError || error instanceof MaliciousFileError) {
    return ErrorSeverity.CRITICAL;
  }

  if (error instanceof DatabaseConnectionError || error instanceof AIInferenceError) {
    return ErrorSeverity.HIGH;
  }

  if (error instanceof ValidationError || error instanceof AuthenticationError) {
    return ErrorSeverity.LOW;
  }

  return ErrorSeverity.MEDIUM;
};

// 创建错误的便捷工厂函数
export const createError = {
  database: (message, details) => new DatabaseError(message, details),
  databaseConnection: (message, details) => new DatabaseConnectionError(message, details),
  aiInference: (message, details) => new AIInferenceError(message, details),
  authentication: (message, details) => new AuthenticationError(message, details),
  authorization: (message, details) => new AuthorizationError(message, details),
  validation: (message, details) => new ValidationError(message, details),
  fileValidation: (message, details) => new FileValidationError(message, details),
  medicalImageValidation: (message, details) => new MedicalImageValidationError(message, details),
  patientNotFound: (details) => new PatientNotFoundError('患者信息不存在', details),
  taskNotFound: (details) => new TaskNotFoundError('评分任务不存在', details),
  duplicateResource: (message, details) => new DuplicateResourceError(message, details),
  security: (message, details) => new SecurityError(message, details),
  maliciousFile: (details) => new MaliciousFileError('检测到恶意文件', details),
  system: (message, details) => new SystemError(message, details),
  configuration: (message, details) => new ConfigurationError(message, details)
};

export {
  AppError,
  DatabaseError,
  DatabaseConnectionError,
  DatabaseQueryError,
  MedicalAIError,
  AIInferenceError,
  AIModelTimeoutError,
  AIModelOverloadError,
  AuthenticationError,
  AuthorizationError,
  TokenExpiredError,
  InvalidTokenError,
  ValidationError,
  FileValidationError,
  MedicalImageValidationError,
  BusinessError,
  PatientNotFoundError,
  TaskNotFoundError,
  TaskStatusError,
  DuplicateResourceError,
  ExternalServiceError,
  CircuitBreakerOpenError,
  SystemError,
  ConfigurationError,
  ResourceExhaustionError,
  SecurityError,
  SuspiciousActivityError,
  MaliciousFileError
};